﻿
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Nacos;
using Nacos.AspNetCore;

namespace BNacosService
{
    public static class NacosServiceCollectionExtensions
    {
        public static IServiceCollection AddNacosService(this IServiceCollection services, IConfiguration Configuration)
        {

            //services.AddNacosAspNetCore(Configuration);
            services.Configure<NacosService>(Configuration.GetSection("nacos"));

            NacosService nacosService = new NacosService();

            Configuration.GetSection("nacos").Bind(nacosService);


            services.AddNacos(configure =>
            {
                // default timeout
                configure.DefaultTimeOut = 8;
                // nacos's endpoint
                configure.ServerAddresses = nacosService.ServerAddresses;// new System.Collections.Generic.List<string> { "http://118.190.140.38:8848/" };
                // namespace
                configure.Namespace = "";
                // listen interval
                configure.ListenInterval = 1000;//1秒钟
            });

            return services;
        }


        //public static void AddNacos(this IServiceCollection services, Action<NacosService> configure)
        //{
        //    var _configure = new NacosService();
        //    configure?.Invoke(_configure);

        //    if (string.IsNullOrEmpty(_configure.ServerAddress))
        //        throw new ArgumentNullException($"ServerAddress参数未配置,示例:http://127.0.0.1:8848,Nacos地址(尽量采用内网访问地址)");

        //    if (string.IsNullOrEmpty(_configure.Loaction))
        //        throw new ArgumentNullException($"服务注册IP参数未配置,示例:127.0.0.1,确保Port属性匹配");

        //    services.AddHttpContextAccessor();


        //    services.AddHttpClient(NacosHttpConsts.HttpService, client =>
        //    {
        //        client.BaseAddress = new Uri(_configure.ServerAddress);
        //    });

        //    services.AddScoped<INacosConfigApi, NacosConfigApi>();
        //}


        public static IApplicationBuilder UseNacosServiceCore1(this IApplicationBuilder app, IOptions<NacosService> fuzlService)
        {
            // 添加健康检查路由地址
            //app.Map("/health", HealthMap);


            //app.UseNacosServiceCore();

            var _serverManager = app.ApplicationServices.GetRequiredService<INacosServerManager>();
            var _clientFactory = app.ApplicationServices.GetRequiredService<IHttpClientFactory>();

            

            var baseUrl =  _serverManager.GetServerAsync("ic-xmzc.yml").GetAwaiter().GetResult();

            if (string.IsNullOrWhiteSpace(baseUrl))
            {
                //return;
            }

            var url = $"{baseUrl}/api/values";

            var client = _clientFactory.CreateClient();


            

            var result = client.GetAsync(url).GetAwaiter().GetResult();

           string strresult = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();


            return app;
        }

 


        public static IApplicationBuilder UseNacosService(this IApplicationBuilder app,IOptions<NacosService> fuzlService)
        {
            // 添加健康检查路由地址
            //app.Map("/health", HealthMap);

            //string Content = "\"ip\":$\"" + fuzlService.Value.Loaction + "\"\r\n \"port\":$\"" + fuzlService.Value.Port + "\"}";
            string Content = "ip:${" + fuzlService.Value.Loaction + "}\r\nport:${" + fuzlService.Value.Port + "}";


  
            var nacosConfigClient = app.ApplicationServices.GetRequiredService<Nacos.INacosConfigClient>();

            nacosConfigClient.PublishConfigAsync(new PublishConfigRequest
            {
                DataId = fuzlService.Value.ServiceName,
                Group = "DEFAULT_GROUP",

                Content = Content//
            });

            

            var val = nacosConfigClient.GetConfigAsync(new Nacos.GetConfigRequest
            {
                DataId = fuzlService.Value.ServiceName
            }).GetAwaiter().GetResult();

            val = nacosConfigClient.GetConfigAsync(new Nacos.GetConfigRequest
            {
                DataId = "ic-auth"
            }).GetAwaiter().GetResult();

            return app;
        }



        public static void HealthMap(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                //context.Request
                await context.Response.WriteAsync("OK");
            });
        }
    }


    //public interface INacosConfigurationParser
    //{
    //    IDictionary<string, string> Parse(string input);
    //}


    //public class XmlConfigurationStringParser : INacosConfigurationParser
    //{
    //    public static XmlConfigurationStringParser Instance = new XmlConfigurationStringParser();

    //    public IDictionary<string, string> Parse(string input)
    //    {
    //        // 具体的解析逻辑
    //        return "";


    //    }
    //}

}
